﻿using System;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using PostIt.Classes;
using PostIt.Static;

namespace PostIt
{
	public partial class FormSettings : Form
	{
		public event SettingsChangedHandler OnSettingsChanged;

	    private string _font;
	    private float _size;

        public FormSettings()
		{
			InitializeComponent();

            LoadSettings();
		}

	    private void LoadSettings()
	    {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load("settings.xml");
            }
            catch (FileNotFoundException)
            {
                // Loads the default if no settingsfile exits
                _size = 24;
                _font = "Al-seana.ttf"; 
            }
            catch (Exception e)
            {
                MessageBox.Show(AppResources.ErrorLoadSettingsMessage + e.Message);
                return;
            }

            try
            {
                XmlNodeList list = doc.GetElementsByTagName("settings");
                foreach (XmlElement element in list)
                {
                    foreach (XmlNode node in element.ChildNodes)
                    {
                        if (node.Name == "font")
                        {
                            _size = float.Parse(node.Attributes[0].Value);
                            _font = node.InnerText;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Loads the default if somethings fails
                _size = 24;
                _font = "Al-seana.ttf";
            }

	        this.comboBoxFontName.SelectedItem = _font;
            this.comboBoxFontSize.SelectedItem = _size.ToString();

	    }

		private void buttonCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

        private void buttonOk_Click(object sender, EventArgs e)
        {
            SettingsChangedHandler ev = OnSettingsChanged;

            float size = Convert.ToSingle(comboBoxFontSize.SelectedItem);
            string font = comboBoxFontName.SelectedItem.ToString();

            if (ev != null)
                OnSettingsChanged(this, new SettingsChangedHandlerArgs() { FontName = font, Size = size });

            this.Close();
        }
	}

    public delegate void SettingsChangedHandler(object sender, SettingsChangedHandlerArgs args);
}
